import { observable, action } from '@/miniprogram_npm/mobx-miniprogram/index';

const guangzhouDistricts = {
    越秀区: 'yuexiu',
    荔湾区: 'liwan',
    海珠区: 'haizhu',
    天河区: 'tianhe',
    白云区: 'baiyun',
    黄埔区: 'huangpu',
    番禺区: 'panyu',
    花都区: 'huadu',
    南沙区: 'nansha',
    从化区: 'conghua',
    增城区: 'zengcheng'
};

export default observable({
    // 股票数据
    stockData: {
        moutai: [],
        icbc: [],
        catl: []
    },
    // 已加载的股票
    stockLoaded: false,
    // 天气数据
    currentWeatherData: {},
    futureWeatherData: [],

    // 电力数据
    electricityData: [],

    /**
     * @param {
     * "close_price", "date", "high", "index", "low", "open_price", "pct_change", "volume"
     * } payload
     */
    setStockData: action(function (data) {
        for (const key in data) {
            data[key].forEach((stock) => {
                this.stockData[key].push({
                    date: stock.date,
                    openPri: stock.open_price,
                    closePri: stock.close_price,
                    highPri: stock.high,
                    lowPri: stock.low,
                    dealNum: stock.volume,
                    increase: stock.pct_change
                });
            });
        }
        this.stockLoaded = true;
    }),

    // 设置天气预测数据
    setWeatherData: action(function (payload) {
        const { monthly, now } = payload;
        this.currentWeatherData = now;
        this.futureWeatherData = monthly;
    }),

    // 设置电力预测数据
    setElectricityData: action(function (payload) {
        this.electricityData = payload;
    }),

    // 获取股票预测数据
    getStockData(name, step) {
        return this.stockData[name].slice(0, step);
    },

    getLoadedStock() {
        return this.stockLoaded;
    },

    // 获取此时天气数据
    getCurrentWeatherData() {
        return this.currentWeatherData;
    },

    // 获取未来天气数据
    getFutureWeatherData(size) {
        return this.futureWeatherData.slice(0, size);
    },

    // 获取某个区的用电量
    getElectricityData(zoneName, size) {
        const target = this.electricityData.slice(0, size ?? 30);
        let xData = [],
            yData = [];

        if (zoneName === '全市合计') {
            yData = target.map((item) => {
                // 将每个区的用电量相加
                const sum = Object.entries(item)
                    .filter(([key, value]) => key !== 'date' && !isNaN(Number(value)))
                    .reduce((acc, [_, value]) => acc + Math.abs(Number(value)), 0);

                return Math.trunc(sum);
            });
            xData = target.map((item) => item.date);
        } else {
            yData = target.map((item) => Math.abs(Math.trunc(item[guangzhouDistricts[zoneName]])));
            xData = target.map((item) => item.date);
        }

        return {
            xData,
            yData
        };
    }
});
